package org.droid.campusorder.manager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import org.droid.campusorder.common.DroidException;

import android.os.Environment;

public class DownManager {
	/*****
	 * 图片下载
	 * 
	 * @param url
	 *            网络上的url
	 * @param localUrl
	 *            本地存储的url
	 */
	public static synchronized void downImage(String url, String localUrl)
			throws Exception {
		if (!isSDCardAvailable()) {
			throw new DroidException.SdcardException(""){};
		}

		URL m;
		InputStream is = null;
		BufferedInputStream bis = null;
		BufferedOutputStream out = null;
		File file;
		m = new URL(url.trim());
		is = (InputStream) m.getContent();
		bis = new BufferedInputStream(is, 1024);
		file = new File(localUrl.trim());
		File dir = file.getParentFile();
		if (!dir.exists()) {
			dir.mkdirs();
		}
		if (!file.exists()) {
			file.createNewFile();
		}

		out = new BufferedOutputStream(new FileOutputStream(file), 1024);

		int len = 0;
		byte[] buffer = new byte[512];
		while ((len = bis.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		out.close();
		bis.close();

	}

	/***
	 * 判断sd卡是否可用
	 * 
	 * @return boolen
	 */
	public static boolean isSDCardAvailable() {
		String mounted = "mounted";
		String temp = Environment.getExternalStorageState();
		boolean b = temp.equals(mounted);
		System.out.println("返回："+b);
		//return temp.equals(mounted);
		return b;
	}
	
	/**
	 * 根据传入的图片在服务器中的请求地址返回图片的文件名
	 * 
	 * @return newName
	 */
	public static String getImageFileName(String oldName) {
		String originalString = oldName;
		String[] result = new String[20];
		StringBuffer stringBuffer = new StringBuffer(originalString);
		StringBuffer stringBuffer1 = stringBuffer.reverse();
		String strTemp = stringBuffer1.toString();
		result = strTemp.split("/");
		StringBuffer stringBuffer2 = new StringBuffer(result[0].toString());
		return (stringBuffer2.reverse().toString());
	}
}
